package com.litree.service.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.litree.service.model.LoginBean;
import com.litree.service.services.IUserService;
import com.litree.service.utils.CommonUtils;
import com.litree.service.utils.Crypt;
import com.litree.service.utils.FileUpAndDown;
import com.litree.service.utils.JSONProxy;
import com.litree.service.utils.ReturnMSGUtils;
import com.litree.service.utils.ReturnMsg;



/**
 * 
 * @author GM
 *
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Controller
public class AuthcController extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(AuthcController.class);

	@Autowired
	private IUserService userService;
	/**
	 * 登陆接口 通过用户名密码获得登陆信息
	 * @param loginName
	 * @param pw
	 * @param response
	 */
	@RequestMapping(method=RequestMethod.GET, value="/authc/loginInfo/{loginName}/{pw}")
	public void getLoginInfo(@PathVariable String loginName,@PathVariable String pw,HttpServletResponse response ) {
		try{			
			List dataList = userService.getLoginInfo(loginName,Crypt.encryptMD5(pw));
			String[] pararms = {loginName,pw};
			if(!CommonUtils.checkParam(pararms,"inputNormalParam")){
				ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.ILLEGAL_PARAM_ERROR, ReturnMsg.ILLEGAL_PARAM_ERROR_DESC+",请重新输入!");
			}else{
				if(!dataList.isEmpty()&&dataList.size()>0){
					Map reslutMap = new HashMap();
					reslutMap.put("token", CommonUtils.encrypt(loginName+","+String.valueOf(System.currentTimeMillis())));
					List roleList = new ArrayList();
					reslutMap.put("lid", ((Map)dataList.get(0)).get("lid"));
					reslutMap.put("loginName", ((Map)dataList.get(0)).get("loginName"));
					reslutMap.put("imageUrl", ((Map)dataList.get(0)).get("imageUrl"));
					for (Object object : dataList) {
						Map objMap = (Map)object;
						objMap.remove("loginName");
						objMap.remove("lid");
						objMap.remove("imageUrl");
						roleList.add(objMap);
					}
					reslutMap.put("roleList", roleList);
					reslutMap.put("code", ReturnMsg.LOGIN_SUCCESS);
					response.getWriter().write(JSON.toJSONString(reslutMap,JSONProxy.SYSTEM_FEATURE));
					logger.info("loginName: "+loginName);
				}else{
					ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.LOGIN_ERROR, ReturnMsg.LOGIN_ERROR_DESC+"!");
				}
			}
		}catch(Exception e){
			try {
				ReturnMSGUtils.sentMsgWithCause(response, "0", ReturnMsg.SELECT_ERROR, ReturnMsg.SELECT_ERROR_DESC, e.toString());
				logger.error(CommonUtils.errMsg(ReturnMsg.SELECT_ERROR, ReturnMsg.SELECT_ERROR_DESC, e));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	//save login info and login_role
	/**
	 * save login info and login_role
	 * 注册接口 
	 * @param bodyStr
	 * @param response
	 * @param request
	 */
	@RequestMapping(method=RequestMethod.POST, value="/authc/loginInfo",consumes = "application/json")
	public void setLoginInfo(@RequestBody String bodyStr,HttpServletResponse response,HttpServletRequest request ) {
		try{			
			LoginBean loginBean = JSON.parseObject(bodyStr, LoginBean.class);
			String[] params = {loginBean.getLoginName(),loginBean.getPw(),loginBean.getNickName(),loginBean.getRoleName()};
			if(!CommonUtils.checkParam(params,"inputNormalParam")){
				ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.ILLEGAL_PARAM_ERROR, ReturnMsg.ILLEGAL_PARAM_ERROR_DESC+",请重新输入!");
			}else{
				if(isLoginNameExist(loginBean.getLoginName())){
					loginBean.setCreated_user(loginBean.getLoginName());
					loginBean.setPw(Crypt.encryptMD5(loginBean.getPw()));
					Integer backInt = userService.setLoginInfo(loginBean);
					ReturnMSGUtils.sentMsg(response, String.valueOf(backInt), ReturnMsg.OPTION_SUCCESS, ReturnMsg.OPTION_SUCCESS_DESC);				
				}else{
					ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.USER_EXITS_ERROR, ReturnMsg.USER_EXITS_ERROR_DESC);
				}
			}
		}catch(Exception e){
			try {
				ReturnMSGUtils.sentMsgWithCause(response, "0", ReturnMsg.INSERT_ERROR, ReturnMsg.INSERT_ERROR_DESC, e.toString());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			logger.error(CommonUtils.errMsg(ReturnMsg.INSERT_ERROR, ReturnMsg.INSERT_ERROR_DESC, e));
		}
	}
	
	private boolean isLoginNameExist(String loginName) {
		List reslutList = userService.getLoginInfo(loginName, null);
		if(reslutList.isEmpty()){
			return true;
		}else{
			return false;			
		}
	}

	/**
	 * 修改密码接口
	 * @param newPw
	 * @param oldPw
	 * @param response
	 */

	@RequestMapping(method=RequestMethod.PUT, value="/authc/loginInfo/updatePw/{oldPw}/{newPw}")
	public void updateLoginPw(@PathVariable String oldPw,@PathVariable String newPw,HttpServletResponse response,HttpServletRequest request) {
		try{
			String[] pararms = {oldPw,newPw};
			if(!CommonUtils.checkParam(pararms,"inputNormalParam")){
				ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.ILLEGAL_PARAM_ERROR, ReturnMsg.ILLEGAL_PARAM_ERROR_DESC+",请重新输入!");
			}else{
				Map token = (Map) request.getAttribute("tokenMap");
				String loginName = (String) token.get("loginName");
				List dataList = userService.getLoginInfo(loginName,Crypt.encryptMD5(oldPw));
				if(!dataList.isEmpty()&&dataList.size()>0){
					Integer backInt = userService.updateLoginPw(loginName,Crypt.encryptMD5(oldPw),Crypt.encryptMD5(newPw));
					ReturnMSGUtils.sentMsg(response, String.valueOf(backInt), ReturnMsg.OPTION_SUCCESS, ReturnMsg.OPTION_SUCCESS_DESC);
				}else{
					ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.PARAM_ERROR, ReturnMsg.PARAM_ERROR_DESC+" 原密码不正确,请重新输入!");
				}
			}
		}catch(Exception e){
			try {
				ReturnMSGUtils.sentMsgWithCause(response, "0", ReturnMsg.OPTION_ERROR, ReturnMsg.OPTION_ERROR_DESC, e.toString());
				logger.error(CommonUtils.errMsg(ReturnMsg.OPTION_ERROR, ReturnMsg.OPTION_ERROR_DESC, e));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * 上传图片接口
	 * @param newPw
	 * @param oldPw
	 * @param response
	 */
	@RequestMapping(method=RequestMethod.PUT, value="/authc/loginInfo/image",consumes = "application/json")
	public void updateLoginImge(@RequestBody String bodyStr,HttpServletResponse response,HttpServletRequest request) {
		try{
			Map tokenMap = (Map) request.getAttribute("tokenMap");
			String loginName = (String) tokenMap.get("loginName");
			Map bodyMap = JSON.parseObject(bodyStr);
			String filaStr = (String) bodyMap.get("data");
			if(filaStr!=null||!("".equals(filaStr))){
				FileUpAndDown.decoderBase64File(filaStr, "orignal_"+loginName+".jpg");
				resizeImage(CommonUtils.getPropertiesBykey("imagePath"),loginName+".jpg");
				Integer backInt = userService.updateLoginImage(loginName,CommonUtils.getPropertiesBykey("imageShowPath")+loginName+".jpg");
				ReturnMSGUtils.sentMsg(response, String.valueOf(backInt), ReturnMsg.OPTION_SUCCESS, ReturnMsg.OPTION_SUCCESS_DESC,"imageUrl",CommonUtils.getPropertiesBykey("imageShowPath")+loginName+".jpg");
			}else{
				ReturnMSGUtils.sentMsg(response, "0", ReturnMsg.PARAM_ERROR, ReturnMsg.PARAM_ERROR_DESC+" 图片文件不正确!");
			}
		}catch(Exception e){
			try {
				ReturnMSGUtils.sentMsgWithCause(response, "0", ReturnMsg.OPTION_ERROR, ReturnMsg.OPTION_ERROR_DESC, e.toString());
				logger.error(CommonUtils.errMsg(ReturnMsg.OPTION_ERROR, ReturnMsg.OPTION_ERROR_DESC, e));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	private void resizeImage(String filePath,String fileName){
		 FileOutputStream out100=null;
		 FileOutputStream out60=null;
		 FileInputStream fis1=null;
		 FileInputStream fis2=null;
	  try {
	   File file1 = new File(filePath,"orignal_"+fileName);
	   File file2 = new File(filePath,"orignal_"+fileName);
	   fis1 = new FileInputStream(file1); 
	   fis2 = new FileInputStream(file2); 
	   out60 = new FileOutputStream(CommonUtils.getPropertiesBykey("imagePath")+"sm_"+fileName);
	   out100 = new FileOutputStream(CommonUtils.getPropertiesBykey("imagePath")+fileName);
	   FileUpAndDown.resizeImage(fis1, out100, 100, "jpg");
	   FileUpAndDown.resizeImage(fis2, out60, 60, "jpg");
	  } catch (Exception e) {
	   e.printStackTrace();
	  }finally{
		   try {
			   if(out100!=null){  
					out100.close();
			   }
			   if(out60!=null){
				   out60.close();
			   }
			   if(fis1!=null){
				   fis1.close();
			   }
			   if(fis2!=null){
				   fis2.close();
			   }
		} catch (IOException e) {
			e.printStackTrace();
		}
	  }
	}
}

